package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    //注入菜品的Service
    @Autowired
    private DishService dishService;

    //注入套餐的Service
    @Autowired
    private SetmealService setmealService;

    //删除分类
    @Override
    public void delete(Long categoryId) {
        //1.根据分类的ID查询菜品表
        //如果关联菜品，抛出业务异常
        LambdaQueryWrapper<Dish> dishLqw = new LambdaQueryWrapper<>();
        dishLqw.eq(Dish::getCategoryId, categoryId);
        int dishcount = dishService.count(dishLqw);
        if (dishcount > 0) {
            //已经关联菜品
            throw new CustomException("已经关联菜品,不允许删除");
        }

        //2.根据分类的ID查询套餐表
        //如果关联套餐，抛出业务异常
        LambdaQueryWrapper<Setmeal> setmealLqw = new LambdaQueryWrapper<>();
        setmealLqw.eq(Setmeal::getCategoryId,categoryId);
        int setmealCount = setmealService.count(setmealLqw);
        if(setmealCount>0){
            throw new CustomException("已经关联套餐,不允许删除");
        }

        //3.删除分类
        removeById(categoryId);
    }
}
